//
//  SWPoetryPagesViewController.swift
//  ChildStory
//
//  Created by linhan on 2016/12/9.
//  Copyright © 2016年 Aiya. All rights reserved.
//

import Foundation
import UIKit
class SWPoetryPagesViewController: SWBaseViewController,UIPageViewControllerDelegate,UIPageViewControllerDataSource,ScrollTabBarDelegate
{
    var poetries:[SWPoetry] = []
    var targetIndex:Int = 0 {
        didSet{
            if _inited
            {
                _tabBar?.selectedIndex = targetIndex
            }
        }
    }
    
    //左边两个 跟 右边 两个用于轮换
    private let VCCacheCount:Int = 3
    private let PageCountPerUnit:Int = 1
    private var _inited:Bool = false
    
    private var _viewControllers:[UIViewController] = []
    private var _tabBar:ScrollTabBar?
    private var _pageController:UIPageViewController?
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setup()
    }
    
    private func setup()
    {
        title = "诗词"
        automaticallyAdjustsScrollViewInsets = false
        view.backgroundColor = UIColor(white: 0.95, alpha: 1)
        
        let items:[String] = poetries.map({$0.name ?? ""})
        let tabBar = ScrollTabBar(frame: CGRectMake(0, navigationBarBottom, view.width, 40))
        tabBar.font = UIFont.systemFont(ofSize: 14)
        tabBar.itemSpacing = 30
        tabBar.selectedColor = UIColor(hex: 0x323131)
        tabBar.unselectedColor = UIColor(hex: 0xa0a0a0)
        tabBar.delegate = self
        tabBar.titleItems = items
        view.addSubview(tabBar)
        _tabBar = tabBar
        
        
        var beginindex:Int = targetIndex - PageCountPerUnit
        if (targetIndex == 0)
        {
            beginindex = 0
        }
        else if (targetIndex >= poetries.count - PageCountPerUnit)
        {
            beginindex = poetries.count - VCCacheCount
        }
        
        for i in beginindex..<beginindex + VCCacheCount
        {
            if (i < 0) {
                continue;
            }
            if (i > poetries.count - 1) {
                break
            }
            let detailViewController:SWPoetryDetailViewController = SWPoetryDetailViewController()
            detailViewController.poetry = poetries.valueAt(i)
            _viewControllers.append(detailViewController)
        }
        
        let pageController:UIPageViewController = UIPageViewController(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil)
        pageController.dataSource = self
        pageController.delegate = self
        
        
        var index:Int = PageCountPerUnit
        if targetIndex == 0
        {
            index = 0
        }
        else if targetIndex == poetries.count - PageCountPerUnit
        {
            index = _viewControllers.count - PageCountPerUnit
        }
        
        var viewControllers:[UIViewController]? = []
        if let firstPage = _viewControllers.valueAt(index)
        {
            viewControllers?.append(firstPage)
        }
        pageController.setViewControllers(viewControllers, direction: .forward, animated: true, completion: nil)
        pageController.view.frame = CGRectMake(0, tabBar.bottom, view.width, view.height - tabBar.bottom)
        addChildViewController(pageController)
        view.addSubview(pageController.view)
        _pageController = pageController
        
        _inited = true
        let aIndex = targetIndex
        targetIndex = aIndex
    }
    
    //跳转到某页
    private func jumbIndex(index target:Int)
    {
        print("jumbIndex:", index)
        var newIndex:Int = max(min(target, poetries.count - 1), 0)
        if newIndex != targetIndex
        {
            let vcCount = _viewControllers.count
            let direction:UIPageViewControllerNavigationDirection = newIndex > targetIndex ? .forward : .reverse
            targetIndex = newIndex
            let beginIndex:Int = min(max(0, targetIndex - PageCountPerUnit), poetries.count - vcCount)
            
            for (i, viewController) in _viewControllers.enumerated()
            {
                let bIndex = beginIndex + i
                if let poetry = poetries.valueAt(bIndex)
                {
                    (viewController as? SWPoetryDetailViewController)?.poetry = poetry
                }
            }
            
            var aIndex:Int = PageCountPerUnit
            if targetIndex == 0
            {
                aIndex = 0
            }
            else if targetIndex == poetries.count - PageCountPerUnit
            {
                aIndex = _viewControllers.count - PageCountPerUnit
            }
            
            var viewControllers:[UIViewController]? = []
            if let firstPage = _viewControllers.valueAt(aIndex)
            {
                viewControllers?.append(firstPage)
            }
            _pageController?.setViewControllers(viewControllers, direction: direction, animated: true, completion: nil)
        }
        
    }
    
    func scrollTabBar(_ tabBar: ScrollTabBar, didSelectIndex index: Int)
    {
        jumbIndex(index: index)
    }
    
    func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController?
    {
        guard let index = _viewControllers.index(of: viewController) else
        {
            return nil
        }
        return _viewControllers.valueAt(index - 1)
    }
    
    func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController?
    {
        guard let index = _viewControllers.index(of: viewController) else
        {
            return nil
        }
        return _viewControllers.valueAt(index + 1)
    }
    
    func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool)
    {
        if let currnetViewController = pageViewController.viewControllers?.last, completed
        {
            let index = _viewControllers.index(of: currnetViewController) ?? -1
            
            // 处理四种特殊情况
            if (targetIndex == 0) {
                if (index == 1) {
                    targetIndex += 1
                }
                return;
            }
            if (targetIndex == 1 && index == 0) {
                targetIndex -= 1;
                return;
            }
            if (targetIndex == poetries.count - 1) {
                if (index == 1) {
                    targetIndex -= 1;
                }
                return;
            }
            if (targetIndex == poetries.count - 2 && index == 2) {
                targetIndex += 1;
                return;
            }
            
            
            if (index == 2)
            {  // 往下翻
                targetIndex += 1;
                if (targetIndex + 1 > poetries.count - 1) {
                    return;
                }
                
                if let detailViewController = _viewControllers.removeAtIndexSafely(0),
                    let poetry = poetries.valueAt(targetIndex + 1)
                {
                    (detailViewController as? SWPoetryDetailViewController)?.poetry = poetry
                    _viewControllers.insert(detailViewController, at: _viewControllers.count)
                }
            }
            else if (index == 0) // 往上翻
            {
                targetIndex -= 1;
                if (targetIndex - 1 < 0) {
                    return;
                }
                
                if let detailViewController = _viewControllers.removeAtIndexSafely(2),
                    let poetry = poetries.valueAt(targetIndex - 1)
                {
                    (detailViewController as? SWPoetryDetailViewController)?.poetry = poetry
                    _viewControllers.insert(detailViewController, at: 0)
                }
            }
            
            
        }//end completed
    }

}
